package com.fsc.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.fsc.entity.properties.Constant;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class OssUtil {

    private static String endpoint="oss-cn-guangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static String accessKeyId ="LTAI5tNsbpo28TRFhAM3jL1o";
    private static String accessKeySecret="x7AB1MosB0T9CBOaFXD1YyDeNtWAGC";
    // 填写Bucket名称，例如examplebucket。
    private static String bucketName ="su-bucket666";
    // 上传文件流。
    public static void uploadImage(byte[] fileByte, String fileName) throws IOException {

        //调用oss方法上传到阿里云
        //第一个参数：Bucket名称
        //第二个参数：上传到oss文件路径和文件名称
        //第三个参数：上传文件输入流
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        //获取上传文件输入流
        InputStream inputStream = new ByteArrayInputStream(fileByte);
        ossClient.putObject(bucketName, fileName, inputStream);

        //把上传后把文件url返回
        //https://xppll.oss-cn-beijing.aliyuncs.com/01.jpg
        ossClient.shutdown();

    }
    public static String uploadFile(MultipartFile file) throws IOException {
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //校验文件大小
        if (file.getSize() > Constant.MAX_FILE_SIZE) {
            throw new FileUploadException("文件大小不能超过10M");
        }
        //保证文件名唯一，去掉uuid中的'-'
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = uuid + fileName;
        String path = "file";
        //拼接
        fileName = path + "/" + fileName;

        //调用oss方法上传到阿里云
        //第一个参数：Bucket名称
        //第二个参数：上传到oss文件路径和文件名称
        //第三个参数：上传文件输入流
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        //获取上传文件输入流
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(bucketName, fileName, inputStream);
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        ossClient.shutdown();
        return url;
    }
    public static String deleteFile(String fileName){
        //删除文件
        //第一个参数：Bucket名称
        //第二个参数：上传到oss文件路径和文件名称
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, fileName);
        ossClient.shutdown();
        return "删除成功";
    }

}
